package com.upsuns.transfer;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 *@Description:<p>文件接收终端</p>
 *@author 王旭
 *@time 2016-1-30 下午5:49:33
 */
public class ServerTerminal implements Terminal {
	
	private int port; //监听端口
	
	private ServerSocketChannel serverChannel;
	
	private SelectionKey key;
	
	
	public ServerTerminal(int port, Selector selector, Integer id) {
		this.port = port;
		try {
			this.serverChannel = ServerSocketChannel.open();
			this.serverChannel.configureBlocking(false);
			this.serverChannel.bind(new InetSocketAddress(port));
			//注册到选择器上
			this.key = serverChannel.register(selector, SelectionKey.OP_ACCEPT, id);
		} catch (IOException e) {
			System.out.println("创建服务失败");
			e.printStackTrace();
		}
	}


	@Override
	public void receive(RandomAccessFile raf, long start, long len) throws IOException {
		
		SocketChannel socketChannel = serverChannel.accept(); //接收客户端请求，获取socket
		socketChannel.configureBlocking(true);
		
		raf.seek(start); //定位文件指针
		FileChannel fileChannel = raf.getChannel();
		//写入数据
		int l = 0;
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while((l = socketChannel.read(buffer)) != -1) {
			buffer.flip(); //准备读数据
			fileChannel.write(buffer);
			start += l;
			raf.seek(start);
			buffer.clear(); //清除原有数据，准备写数据。
		}
		
		fileChannel.close();
		socketChannel.close();
		serverChannel.close();
		
	}


	@Override
	public void send(RandomAccessFile raf, long start, long len) {
		
	}


	public int getPort() {
		return port;
	}


	public void setPort(int port) {
		this.port = port;
	}

}
